import config from "config";
import React from "react";
import httpFetch from "share/httpFetch";
import configureStore from "stores";
import {
  setUser,
  setLoginUser,
  setCompany,
  setLoginCompany,
  setTenant,
  setProfile,
  setLoginProfile,
  setLanguageList,
  setUserPermission,
  setUserPermissionAllMenus,
  setNewPermissionSortedMenus,
  setCompanyConfiguration,
  setIsOldCompany,
  setLoginOptions,
  setOptions,
} from "actions/login";
import { setEnableDepCompany, setResourceKey } from "actions/setting";
import { message } from "antd";
import {
  setLanguage,
  setTenantMode,
  setAdminMode,
  setControlConfig,
} from "actions/main";
import errorMessage from "share/errorMessage";
import { getLanguageObjByCode } from "share/utils";
import {
  getBrowserInfo,
  messages,
  MD5,
  deepFullCopy,
  removeToken,
} from "share/common";
import ExtendFieldService from "containers/enterprise-manage/extend-field/extend-field.service.js";
import OrgService from "containers/enterprise-manage/org-structure/org-structure.service";
import menuRoute from "routes/menuRoute";
import RSService from "containers/permission-setting/role-menu-setting/role-menu-setting.service";

export default {
  // 切换语言并设置
  changeLanguage(value) {
    let code = value;
    if (value === "zh_cn") {
      code = "zh_CN";
    } else if (value === "zh_tw") {
      code = "zh_TW";
    }
    return httpFetch
      .post(`${config.baseUrl}/api/users/language/${code}`)
      .then((response) => {
        const language = getLanguageObjByCode(value);
        configureStore.store.dispatch(setLanguage(language));
        window.location.reload();
      })
      .catch((e) => {
        message.error(
          messages("components.key1" /* 切换语言失败，请重新切换 */)
        );
      });
  },

  // 得到用户信息并存储信息
  getUser() {
    return new Promise((resolve, reject) => {
      // header加参数
      const accountHeader = {
        "x-helios-client": "web",
        "x-helios-clientVersion": `${getBrowserInfo().name}:${getBrowserInfo().version
          }`,
        "x-helios-appVersion": config.heliosVersion,
      };
      httpFetch
        .get(`${config.baseUrl}/api/account`, {}, accountHeader)
        .then((response) => {
          const user = response.data;
          // 根据老中控设置
          this.getTenant(user.tenantId);
          if (user.language === null) {
            // 请初始化集团语言
            message.warn(messages("components.key2" /* 请初始化集团语言 */));
            return;
          }
          const localLanguage = localStorage.getItem("hly.language");
          if (!localLanguage) {
            const language = getLanguageObjByCode(user.language);
            configureStore.store.dispatch(setLanguage(language));
          }
          configureStore.store.dispatch(setUser(response.data));
          configureStore.store.dispatch(setLoginUser(response.data));
          if (window.localStorage.getItem("mail_approve")) {
            // 如果是邮件审批 与代办消息，如果是集团模式，需要切换到公司模式，再调整
            configureStore.store.dispatch(setTenantMode(false));
            // bug31876--王若楠
            // mainSelf.switchCompanyOrTenant(user.companyId, false);
            // let originUrl = window.localStorage.getItem('mail_approve');
            // todo
            // 先这样做简单处理，目前新老权限在一起，待以后优化
            // 可以用事件或者回调函数
            setTimeout(() => {
              // bug31876--王若楠
              // window.location.href = originUrl;
              window.localStorage.removeItem("mail_approve");
            }, 2000);
            window.localStorage.removeItem("mail_approve");
          } else {
            // 设置 租户/公司 模式
            // configureStore.store.dispatch(setTenantMode(user.hasTenantRole));
            // bug 31054
            // 切换公司也需要刷新此接口，如果不使用sessionStorage 就一直无法切换公司
            if (sessionStorage.getItem("HLY-RoleType")) {
              const roleType = JSON.parse(
                sessionStorage.getItem("HLY-RoleType")
              );
              configureStore.store.dispatch(
                setTenantMode(roleType === "tenant")
              );
            } else if (user.enableNewPermission) {
              configureStore.store.dispatch(setTenantMode(user.hasTenantRole));
            } else {
              configureStore.store.dispatch(
                setTenantMode(
                  React.Component.prototype.checkAuthorities(
                    "ROLE_TENANT_ADMIN"
                  )
                )
              );
            }
            // 设置 管理员/员工 模式
            if (sessionStorage.getItem("HLY-AdminRoleType")) {
              const roleType = sessionStorage.getItem("HLY-AdminRoleType");
              configureStore.store.dispatch(setAdminMode(roleType === "admin"));
            } else {
              // 无论是什么权限，都默认设置为员工模式
              configureStore.store.dispatch(setAdminMode(false));
              // configureStore.store.dispatch(setAdminMode(user.adminMode));--新权限
              // configureStore.store.dispatch(setAdminMode(React.Component.prototype.checkAuthorities(['ROLE_TENANT_ADMIN', 'ROLE_COMPANY_ADMIN'])))--老权限
            }
          }
          resolve(response);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err.response);
        });
    });
  },

  /**
   * 得到用户信息
   * @return {*|Promise.<TResult>}
   */
  getInfo() {
    // 可以异步获取
    this.initService();
    this.getResourceKey();
    return this.getUser()
      .then((userInfo) =>
        this.getUserIsGAndA().then(res => {
          return Promise.all([
            this.getCompany(),
            this.getProfile(),
            this.getAllModePermissionMenus(userInfo.data),
            this.getCompanyConfiguration(),
            this.getIsOldCompany(),
            this.getLanguageList(),
            // this.getOptions(),
          ])
        })
      )
      .catch((err) => {
        console.log("getUser-err", err);
        throw err;
      });
  },

  // 系统初始化时一次性获取此用户拥有的所有菜单
  getAllPermissionMenu(userInfo) {
    const arr = [
      ["tenant", "admin"],
      ["tenant", undefined],
      [undefined, "admin"],
      [undefined, undefined],
    ];
    let apis = [arr[3]];
    // 根据用户是否拥有tenant和admin权限决定要掉几个接口
    if (userInfo.hasTenantRole && !userInfo.adminMode) {
      apis = [arr[0], arr[1], arr[3]];
    }
    if (userInfo.adminMode && !userInfo.hasTenantRole) {
      apis = [arr[0], arr[2], arr[3]];
    }
    if (userInfo.adminMode && userInfo.hasTenantRole) {
      apis = [arr[0], arr[1], arr[2], arr[3]];
    }
    const shouldRequestList = apis.map((item) =>
      this.getPermissionByMode(item[0], item[1])
    );
    if (config.appEnv === 'dev') {
      shouldRequestList.push(this.getFakePermissionByMode("tenant", undefined));
    }
    return Promise.all(shouldRequestList);
  },

  // 新权限用户的所有菜单
  getAllModePermissionMenus(userInfo) {
    if (!userInfo.enableNewPermission) {
      return;
    }
    return new Promise((resolve, reject) => {
      this.getAllPermissionMenu(userInfo)
        .then((res) => {
          // 因为同一个菜单可能会在不同模式下都展示，所以要对获取到的所有菜单进行去重，整合
          const arr = [];
          res.map((item) => {
            const menu =
              item.data.userResourcePermission.funcPermissionDetailDTOS;
            if (menu && menu.length) {
              menu.map((menuItem) => {
                if (arr.length) {
                  let bool = false;
                  arr.map((newMenu) => {
                    if (newMenu.key === menuItem.key) {
                      bool = true;
                      // 因为一个菜单可能会在多种模式下显示，这步是集齐所有显示属性
                      newMenu.menuShowAttr.push(menuItem.menuShowAttr);
                    }
                  });
                  if (!bool) {
                    menuItem.menuShowAttr = [menuItem.menuShowAttr];
                    arr.push(menuItem);
                  }
                } else {
                  menuItem.menuShowAttr = [menuItem.menuShowAttr];
                  arr.push(menuItem);
                }
              });
            }
          });
          // console.log(
          //   "arr",
          //   arr.find((item) => item.key === "applications")
          // );
          console.log('arr=======', arr)
          console.log("sessionStorage", typeof sessionStorage.getItem('isConsumptions'))
          let listName = [];
          let list = [];
          let consumptionList = JSON.parse(sessionStorage.getItem('isConsumptions') || '[]')
          if (consumptionList && consumptionList.length > 0) {
            consumptionList.map((item) => {
              if (!item.show) {
                listName.push(item.name)
              }
            })
            arr.map(item => {
              if (!listName.includes(item.resourceName)) {
                list.push(item)
              }
              this.handleNewPermissionMenu(list);
            })
          } else {
            this.handleNewPermissionMenu(arr);
          }
          // 所有不为RW的菜单都算入控制范围
          const controlMenu = arr
            .filter((menu) => menu.operationType === "R")
            .map((menu) => menu.key);
          configureStore.store.dispatch(setControlConfig(controlMenu));
          // userPermissionAllMenus 是新权限用户拥有的未经排序，未组合成树形结构的由单个菜单对象组成的数组
          configureStore.store.dispatch(setUserPermissionAllMenus(arr));
          resolve(res);
        })
        .catch((err) => {
          errorMessage(err.response);
          reject(err);
        });
    });
  },

  // 赋予每个菜单具有的显示属性，应该在哪种组合模式下展示
  setMenuShowAttr(isTenant, isAdmin) {
    const args = [
      {
        isTenant: "tenant",
        isAdmin: "admin",
        menuShowAttr: { tenant: true, admin: true },
      },
      {
        isTenant: "tenant",
        isAdmin: undefined,
        menuShowAttr: { tenant: true, employee: true },
      },
      {
        isTenant: undefined,
        isAdmin: "admin",
        menuShowAttr: { company: true, admin: true },
      },
      {
        isTenant: undefined,
        isAdmin: undefined,
        menuShowAttr: { company: true, employee: true },
      },
    ];
    let menuShowAttr = {};
    args.map((item) => {
      if (item.isTenant === isTenant && item.isAdmin === isAdmin) {
        menuShowAttr = item.menuShowAttr;
      }
    });
    return menuShowAttr;
  },

  // 分模式获取菜单，通过参数获取对应模式的菜单
  getPermissionByMode(isTenant, isAdmin) {
    const params = {
      mode: isAdmin === "admin" ? "ADMIN" : undefined,
    };
    return httpFetch
      .get(
        `${config.baseUrl}/api/authorization/policy/user/permission${isTenant === "tenant" ? "?roleType=TENANT" : ""
        }`,
        params
      )
      .then((response) => {
        // 严禁使用userPermission里面的userResourcePermission.funcPermissionDetailDTOS。不准确，已废弃
        configureStore.store.dispatch(setUserPermission(response.data));
        const menuShowAttr = this.setMenuShowAttr(isTenant, isAdmin);
        response.data.userResourcePermission.funcPermissionDetailDTOS.map(
          (item) => {
            item.menuShowAttr = menuShowAttr;
          }
        );
        // 这里这里
        console.log("response", response)
        return response;
      });
  },

  getFakePermissionByMode(isTenant, isAdmin) {
    return Promise.resolve({
      data: {
        userId: "6",
        userLanguage: "zh_cn",
        tenantId: "1187657433422495746",
        hasTenantRole: true,
        adminMode: true,
        belongFuncResourcePermission: [
          1187657462363193346, 1187657463424352258, 1187657463160111105,
          1229774455308312577, 1187657464191909889, 1240102747735420929,
          1362973987071619074, 1187657464015749122,
        ],
        userResourcePermission: {
          funcPermissionDetailDTOS: [
            // {
            //   functionCode: "done",
            //   key: "done",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceName: "已办事项",
            //   resourceOrder: 8,
            // },
            // {
            //   functionCode: "done-approved",
            //   key: "done-approved",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceName: "已处理",
            //   resourceOrder: 8,
            // },

            // {
            //   defaultReadable: "1",
            //   functionCode: "applications",
            //   id: "1287657461708881922",
            //   key: "applications",
            //   operationType: "RW",
            //   parentId: "0",
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "申请单",
            //   resourceOrder: 8,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },
            // {
            //   defaultReadable: "1",
            //   functionCode: "todo",
            //   id: "1287657461708881923",
            //   key: "todo",
            //   operationType: "RW",
            //   parentId: "0",
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "待办事项",
            //   resourceOrder: 1,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },
            // {
            //   defaultReadable: "1",
            //   functionCode: "to-be-submit",
            //   id: "1287657461708881924",
            //   key: "to-be-submit",
            //   operationType: "RW",
            //   parentId: "2901", // todo
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "待提交",
            //   resourceOrder: 1,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },
            // {
            //   defaultReadable: "1",
            //   functionCode: "to-be-approve",
            //   id: "1287657461708881925",
            //   key: "to-be-approve",
            //   operationType: "RW",
            //   parentId: "2901",  // todo
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "待处理",
            //   resourceOrder: 1,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },
            // {
            //   defaultReadable: "1",
            //   functionCode: "my-travel",
            //   id: "1287657461708881925",
            //   key: "my-travel",
            //   operationType: "RW",
            //   parentId: "0",
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "我的出行",
            //   resourceOrder: 1,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },{
            //   defaultReadable: "1",
            //   functionCode: "travel-and-booking",
            //   id: "1287657461708881925",
            //   key: "travel-and-booking",
            //   operationType: "RW",
            //   parentId: "0", // my-travel
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "出行及预订",
            //   resourceOrder: 1,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },
            // {
            //   defaultReadable: "1",
            //   functionCode: "consumptions",
            //   id: "1287657461708881926",
            //   key: "consumptions",
            //   operationType: "RW",
            //   parentId: "0",
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "消费记录",
            //   resourceOrder: 1,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },
            // {
            //   defaultReadable: "1",
            //   functionCode: "union",
            //   id: "1387657461708881937",
            //   key: "union",
            //   operationType: "RW",
            //   parentId: "0",
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "工会",
            //   resourceOrder: 1,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },
            // {
            //   defaultReadable: "1",
            //   functionCode: "union-request",
            //   id: "1387657461708881937",
            //   key: "union-request",
            //   operationType: "RW",
            //   parentId: "2901", // union
            //   permissionId: "1287657460358316033",
            //   resourceCreatedDate: "2019-10-24 14:36:03",
            //   resourceId: "29030300",
            //   resourceName: "工会申请单",
            //   resourceOrder: 1,
            //   resourceScene: 0,
            //   tenantId: "1187617433422495746",
            // },
            {
              defaultReadable: "1",
              functionCode: "expense-report",
              id: "1387657461708881937",
              key: "expense-report",
              operationType: "RW",
              parentId: "2901",  // union
              permissionId: "1287657460358316033",
              resourceCreatedDate: "2019-10-24 14:36:03",
              resourceId: "29030300",
              resourceName: "报销单",
              resourceOrder: 1,
              resourceScene: 0,
              tenantId: "1187617433422495746",
            },
          ],
        },
        authorizationPermissions: [],
      },
    }).then((response) => {
      // 严禁使用userPermission里面的userResourcePermission.funcPermissionDetailDTOS。不准确，已废弃
      configureStore.store.dispatch(setUserPermission(response.data));
      const menuShowAttr = this.setMenuShowAttr(isTenant, isAdmin);
      response.data.userResourcePermission.funcPermissionDetailDTOS.map(
        (item) => {
          item.menuShowAttr = menuShowAttr;
        }
      );
      return response;
    });
  },

  // 把新权限用户拥有的排序好的菜单 newPermissionSortedMenus 存至redux，
  handleNewPermissionMenu(arr) {
    const menu = this.getNewPermissionMenu(menuRoute.menu, arr);
    const sortedMenu = this.sortNewPermissionMenu(menu);
    configureStore.store.dispatch(setNewPermissionSortedMenus(sortedMenu));
    window.configureStore = configureStore
  },

  /*
   * 结合后端返回的所有菜单，过滤前台应该显示的 菜单
   * 添加后端返回的菜单序号，名称（多语言），图标
   * @param allMenu 前台的所有菜单
   * @param userPermissionAllMenus 当前用户能看见所有菜单，后端返回
   * @return 返回当前模式可以看到的菜单
   * */
  getNewPermissionMenu(allMenu, userPermissionAllMenus) {
    const newMenu = [];
    allMenu.map((item) => {
      const _item = keyIsInPermissionAllMenus(item.key, userPermissionAllMenus);
      if (_item) {
        item.menuShowAttr = _item.menuShowAttr;
        item.defaultReadable = _item.defaultReadable;
        item.operationType = _item.operationType;
        const obj = deepFullCopy(item);
        obj.resourceOrder = _item.resourceOrder;
        obj.menuName = _item.resourceName;
        obj.ficon = _item.resourceImage;
        obj.resourceCreatedDate = new Date(_item.resourceCreatedDate).getTime();
        if (item.subMenu && item.subMenu.length) {
          obj.subMenu = [];
          item.subMenu.map((sub) => {
            const _item2 = keyIsInPermissionAllMenus(
              sub.key,
              userPermissionAllMenus
            );
            if (_item2) {
              sub.menuShowAttr = _item2.menuShowAttr;
              sub.defaultReadable = _item2.defaultReadable;
              sub.operationType = _item2.operationType;
              sub.resourceOrder = _item2.resourceOrder;
              sub.menuName = _item2.resourceName;
              sub.ficon = _item2.resourceImage;
              sub.resourceCreatedDate = new Date(
                _item2.resourceCreatedDate
              ).getTime();
              obj.subMenu.push(sub);
            }
          });
        }
        newMenu.push(obj);
      }
    });
    return newMenu;

    // 要给前端的菜单对象加上后端返回的序号属性
    function keyIsInPermissionAllMenus(key, userPermissionAllMenus) {
      let _item = null;
      userPermissionAllMenus.map((item) => {
        if (key === item.key) {
          _item = item;
        }
      });
      return _item;
    }
  },

  /*
   * 对菜单排序，
   * @param menuList 菜单列表
   * @return 排序之后菜单
   * 对整个应用的菜单排序，
   * 先对一级菜单，再对二级菜单
   * 传入结构是
   * [
   * {
   * subMenu:[{},{}]
   * },{},{},...]
   * */
  sortNewPermissionMenu(menuList) {
    const firstMenu = RSService.sortMenuList(menuList, "resourceOrder");
    firstMenu.map((item) => {
      if (item.subMenu) {
        item.subMenu = RSService.sortMenuList(item.subMenu, "resourceOrder");
      }
    });
    return firstMenu;
  },

  getResourceKey() {
    return httpFetch
      .get(`${config.baseUrl}/api/security/resource/key/list`, {})
      .then((res) => {
        configureStore.store.dispatch(setResourceKey(res.data));
      });
  },
  initService() {
    OrgService.checkEnableDepCompany().then((res) => {
      configureStore.store.dispatch(
        setEnableDepCompany(res.data.companyControlStatus)
      );
    });
  },
  getLanguageList() {
    return httpFetch
      .post(`${config.baseUrl}/api/lov/language/zh_CN`, {})
      .then((response) => {
        configureStore.store.dispatch(setLanguageList(response.data));
      });
  },

  // 得到公司信息并存储在redux内
  getCompany() {
    return httpFetch
      .get(`${config.baseUrl}/api/my/companies`, {})
      .then((response) => {
        if (response.data.tokenStorage === "session") {
          if (localStorage.getItem("hly.token")) {
            sessionStorage.setItem(
              "hly.token",
              localStorage.getItem("hly.token")
            );
            localStorage.removeItem("hly.token");
          }
          if (!sessionStorage.getItem("hly.token")) {
            sessionStorage.setItem(
              "hly.token",
              JSON.stringify(configureStore.store.getState().main.authToken)
            );
          }
        } else if (sessionStorage.getItem("hly.token")) {
          // 在安全设置页面，从 需要 设置为 不需要 每次登录，然后走这个函数
          const t = sessionStorage.getItem("hly.token");
          localStorage.setItem("hly.token", t);
          sessionStorage.removeItem("hly.token");
        }
        configureStore.store.dispatch(setCompany(response.data));
        configureStore.store.dispatch(setLoginCompany(response.data));
        return response;
      });
  },
  // 临时更换登录信息
  changeLoginInfo(userOID) {
    this.lastUserOID = userOID;

    return Promise.all([
      this.getUserInfo(userOID),
      this.getTmpFp(userOID),
      this.getTmpCompany(userOID),
      // this.getTmpOptions(userOID),
    ]);
  },
  getTmpUser(userOID) {
    return httpFetch
      .get(`${config.baseUrl}/api/users/proxy/${userOID}`, {})
      .then((response) => {
        if (userOID !== this.lastUserOID) return;

        configureStore.store.dispatch(setUser(response.data));
      });
  },
  getTmpCompany(userOID) {
    return httpFetch
      .get(`${config.baseUrl}/api/company/user`, { useroid: userOID })
      .then((response) => {
        if (userOID !== this.lastUserOID) return;
        configureStore.store.dispatch(setCompany(response.data));
      });
  },
  getTmpFp(userOID) {
    return httpFetch
      .get(`${config.baseUrl}/api/function/profiles/${userOID}`, {})
      .then((response) => {
        if (userOID !== this.lastUserOID) return;

        configureStore.store.dispatch(setProfile(response.data));
      });
  },
  getTmpOptions(userOID) {
    return httpFetch.get(`${config.baseUrl}/api/options`).then((response) => {
      if (userOID !== this.lastUserOID) return;
      configureStore.store.dispatch(setOptions(response.data));
      return response;
    });
  },
  getFpByUserOID(userOID) {
    return httpFetch
      .get(`${config.baseUrl}/api/function/profiles/${userOID}`, {})
      .then((response) => response);
  },
  getCompanyByUserOID(userOID) {
    return httpFetch
      .get(`${config.baseUrl}/api/company/user`, { useroid: userOID })
      .then((response) => response);
  },

  // 得到集团信息并存储在redux内
  getTenant(tenantId) {
    return httpFetch
      .get(`${config.baseUrl}/api/tenant/getById?tenantId=${tenantId}`, {})
      .then((response) => {
        configureStore.store.dispatch(setTenant(response.data));
      });
  },

  // 得到公司配置并存储在redux内
  getCompanyConfiguration() {
    return httpFetch
      .get(`${config.baseUrl}/api/company/configurations/user`)
      .then((response) => {
        configureStore.store.dispatch(setCompanyConfiguration(response.data));
        return response;
      });
  },

  //得到新版fp
  getOptions(userOID = configureStore.store.getState().login.user.userOID) {
    return httpFetch
      .get(`${config.baseUrl}/api/options`, { userOID })
      .then((response) => {
        configureStore.store.dispatch(setOptions(response.data));
        configureStore.store.dispatch(setLoginOptions(response.data));
      });
  },

  // 得到公司的functionProfile并存储在redux内
  getProfile() {
    return new Promise((resolve, reject) => {
      httpFetch
        .get(`${config.baseUrl}/api/function/profiles`)
        .then((tanantProfile) => {
          ExtendFieldService.getPersonCustomForm()
            .then((user_extend_field_form) => {
              tanantProfile.data["_self.company.contact.custom.form"] =
                user_extend_field_form.data.formOID;
              configureStore.store.dispatch(setProfile(tanantProfile.data));
              configureStore.store.dispatch(
                setLoginProfile(tanantProfile.data)
              );
              resolve(tanantProfile);
            })
            .catch(() => {
              configureStore.store.dispatch(setProfile(tanantProfile.data));
              configureStore.store.dispatch(
                setLoginProfile(tanantProfile.data)
              );
              resolve(tanantProfile);
            });
        });
    });
  },
  // 得到是否为老公司并存储在redux内
  getIsOldCompany() {
    return httpFetch
      .get(`${config.baseUrl}/api/tenant/check/exsit/company/his`)
      .then((response) => {
        configureStore.store.dispatch(setIsOldCompany(response.data));
      });
  },
  // 根据租户查询账套信息
  getSetOfBooksByTenant() {
    return httpFetch.get(`${config.baseUrl}/api/setOfBooks/by/tenant`);
  },

  // 地图搜索,按照域名区分使用腾讯地图还是谷歌地图
  // 你觉得这块看着不好看？
  // IP定位？不准
  // 之后有更多国外业务怎么办？
  // 欢迎有更好的想法
  searchLocation(keyword) {
    const foreignHosts = [
      "console-my.huilianyi.com",
      "console-sg.huilianyi.com",
      "portal.spendia.jp",
      "sit.spendia.jp",
      "stage.spendia.jp",
    ];
    if (foreignHosts.indexOf(location.host) === -1) {
      const { tenantMode } = configureStore.store.getState().main;
      const sig = MD5(
        `/ws/place/v1/suggestion?key=${config.tencentMapKey
        }&keyword=${keyword}&region=${tenantMode ? "&roleType=TENANT" : ""}${config.tencentSecretKey
        }`
      );
      const params = {
        region: "",
        key: config.tencentMapKey,
        keyword: encodeURIComponent(keyword),
        sig,
      };
      return httpFetch
        .get(`${config.baseUrl}/ws/place/v1/suggestion`, params)
        .then(
          (res) =>
            new Promise((resolve) => {
              if (res.data && res.data.data) {
                const result = [];
                res.data.data.map((item) => {
                  result.push({
                    title: item.title,
                    address: `${item.province}${item.city}${item.district}${item.address}`,
                    location: item.location,
                  });
                });
                resolve(result);
              } else {
                resolve([]);
              }
            })
        );
    }
    const params = {
      input: encodeURIComponent(keyword),
      inputtype: "textquery",
      fields: "formatted_address,name,rating,geometry",
      key: config.googleMapKey,
    };
    return httpFetch
      .get(`${config.baseUrl}/maps/api/place/findplacefromtext/json`, params)
      .then(
        (res) =>
          new Promise((resolve) => {
            if (res.data && res.data.candidates) {
              const result = [];
              res.data.candidates.map((candidate) => {
                result.push({
                  title: candidate.name,
                  address: candidate.formatted_address,
                  location: candidate.geometry.location,
                });
              });
              resolve(result);
            } else {
              resolve([]);
            }
          })
      );
  },

  // 获取国家
  getCountries(params) {
    return httpFetch.get(
      `${config.accountingUrl}/location-service/api/localization/query/country`,
      params
    );
  },

  // 根据国家code获取城市信息
  getCities(params) {
    return httpFetch.get(
      `${config.accountingUrl}/location-service/api/localization/query/all/address`,
      params
    );
  },

  /**
   * 自定义参数获取费用类型
   * @param params
   * {
        userOID 用户OID
        expenseReportOID 报销单OID（与申请单OID互斥）
        applicationOID 申请单OID（与报销单OID互斥）
        createManually 是否可手工添加 boolean
        pasteInvoiceNeeded 是否需要贴票 boolean
        multipleInvoiceSupported 是否支持多发票 boolean
   * }
   */
  getExpenseTypesByCustomParams(params) {
    params.subsidyType = 98;
    return httpFetch.post(`${config.baseUrl}/api/expense/type/byUser`, params);
  },

  // 根据表单OID和用户OID获取费用类型
  getExpenseTypesByFormOID(param) {
    const { formOID } = param;
    delete param.formOID;
    return httpFetch.get(
      `${config.baseUrl}/api/custom/forms/${formOID}/selected/expense/types`,
      param
    );
  },

  // 根据表单OID获取费用类型
  getExpenseTypesByFormOIDV2(param) {
    const { formOID } = param;
    delete param.formOID;
    return httpFetch.get(
      `${config.baseUrl}/api/v2/custom/forms/${formOID}/selected/expense/types`,
      param
    );
  },

  // 根据表单OID获取费用类型的选择历史
  getExpenseTypesHistoryByFormOID(param) {
    return httpFetch.get(
      `${config.baseUrl}/api/application/budget/type/history`,
      param
    );
  },

  // 根据公司OID获取费用类型
  getExpenseTypeByCompanyOID(companyOID) {
    return httpFetch.get(
      `${config.baseUrl}/api/expense/types?companyOID=${companyOID}`
    );
  },

  // 根据UserOID获取费用类型
  getExpenseTypeByUserOID(userOID) {
    return httpFetch.get(
      `${config.baseUrl}/api/expense/types?userOID=${userOID}`
    );
  },

  // 获取费用大类型
  getExpenseTypeCategory(setOfBooksId) {
    const params = { setOfBooksId };
    return httpFetch.get(
      `${config.baseUrl}/api/expense/types/category`,
      params
    );
  },

  // 根据账套获得费用类型
  getExpenseTypesBySetOfBooks(
    setOfBooksId,
    createdManually = true,
    enabled = true,
    name
  ) {
    return httpFetch.get(
      `${config.baseUrl}/invoice/api/expense/types/groupby/category`,
      {
        setOfBooksId,
        createdManually,
        enabled,
        name, // 小类名称，模糊搜索
      }
    );
  },

  // 根据费用OID获取费用类型
  getExpenseTypeByOID(expenseTypeOID) {
    return httpFetch.get(
      `${config.baseUrl}/api/expense/types/${expenseTypeOID}`
    );
  },

  // 根据费用id获取费用类型
  getExpenseTypeById(id) {
    return httpFetch.get(`${config.baseUrl}/api/expense/types/select/${id}`);
  },
  // 根据费用OID获取费用详情
  getInvoiceDetail(invoiceOID, params = {}) {
    return httpFetch.get(
      `${config.baseUrl}/api/invoices/${invoiceOID}`,
      params
    );
  },

   /**
   * 根据oid查询费用信息
   * @param params
   */
   getDIDIOid(invoiceOID, params = {}){
    return httpFetch.get(`${config.baseUrl}/api/didiV3/queryOrderList/${invoiceOID}`, params);
  },

  // 根据语言和本位币获取货币列表
  getCurrencyList(
    currencyCode = configureStore.store.getState().login.company.baseCurrency,
    language = "zh_CN"
  ) {
    const param = {
      currencyCode,
      language,
    };
    return httpFetch.get(`${config.baseUrl}/api/currencyI18n`, param);
  },

  /**
   * 根据语言获得货币列表
   * @param language 用户语言 默认zh_cn
   * @param userOId 用户oid
   * @param enable 是否只查询启用币种（true-启用，false-不启用，null-全部）
   * @param withRate 是否查询汇率(true-查询汇率，false-不查询汇率）
   * @param jobId 岗位id
   * @param setOfBooksId 帐套id(setOfBooksId jobId同时传以setOfBooksId为准)
   */
  getAllCurrencyByLanguage(
    language = "zh_cn",
    userOId = configureStore.store.getState().login.user.userOID,
    enable = null,
    withRate = true,
    jobId,
    setOfBooksId
  ) {
    const params = {
      userOId,
      language,
      enable,
      withRate,
      jobId,
      setOfBooksId,
    };
    return httpFetch.get(
      `${config.baseUrl}/api/currency/status/query/by/setOfBooksId`,
      params
    );
  },

  // 获取汇率
  getExchangeRate(currency, currencyDate) {
    const param = {
      currency,
      currencyDate,
    };
    return httpFetch.get(
      `${config.baseUrl}/api/company/standard/currency/get`,
      param
    );
  },

  // 根据用户OID获得用户
  getUserByOID(userOID) {
    return httpFetch.get(`${config.baseUrl}/api/users/oid/${userOID}`);
  },

  // 得到商务卡消费记录，分页
  getBusinessCardConsumptionList(
    bankCard,
    used,
    ownerOID,
    page,
    size,
    currMaxID,
    invoiceOid = null,
    isDidi
  ) {
    const params = {
      ownerOID,
      page,
      size,
      currMaxID,
      invoiceOid,
      isDidi: isDidi || false,
    };
    return httpFetch.get(
      `${config.baseUrl}/api/bankcard/transactions/${bankCard}/${used}`,
      params
    );
  },
  /**
   * 获取滴滴消费记录
   * @param {String} start
   * @param {String} end
   */
  getDiDiList(pagination, searchCondition) {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchCondition
    };
    return new Promise((resolve, reject) => {
      httpFetch.get(`${config.baseUrl}/api/didiV3/queryOrderList`, params).then((res) => {
        resolve(res);
      }).catch((err) => {
        errorMessage(err.response);
        reject(err.response);
      });
    });
  },
  /**
   * 获取被选中的公务卡明细的总金额
   * @param data
   * @returns {*}
   */
  getBusinessCardTotalAmount(data) {
    return httpFetch.post(
      `/invoice/api/bankTransaction/cal/total_amount`,
      data
    );
  },
  // 得到表单内容
  getFormDetail(formId) {
    return httpFetch.get(`${config.baseUrl}/api/custom/forms/${formId}`);
  },

  // 获取用户信息
  getUserInfo(userOID) {
    return httpFetch.get(`${config.baseUrl}/api/users/v2/${userOID}`);
  },

  // 获取岗位信息
  getJobInfo(jobId) {
    return httpFetch.get(`${config.baseUrl}/api/user/jobs/${jobId}`);
  },

  // 得到成本中心
  getCostCenter(setOfBooksId) {
    const params = { setOfBooksId };
    return httpFetch.get(`${config.baseUrl}/api/cost/center/company`, params);
  },

  // 得到级联成本中心，启用中 & 被附属
  getLinkageCostCenter(setOfBooksId) {
    const params = { setOfBooksId };
    return httpFetch.get(
      `${config.baseUrl}/api/cost/centers/parents/by/setofbooksid`,
      params
    );
  },

  // 得到公司银行账户
  getCompanyBank(setOfBooksId, page, size) {
    const params = { setOfBooksId, page, size };
    return httpFetch.get(
      `${config.baseUrl}/api/CompanyBank/get/by/setOfBooksId`,
      params
    );
  },

  // 获取汇率容差配置
  getRateDeviation(tenantId, setOfBooksId) {
    const params = { tenantId, setOfBooksId };
    return httpFetch.get(
      `${config.baseUrl}/api/tenant/config/by/tenantId`,
      params
    );
  },

  // 根据OID获得值列表
  getCustomEnumerationsByOID(enumOID) {
    return httpFetch.get(
      `${config.baseUrl}/api/custom/enumerations/${enumOID}/items/v2`
    );
  },

  // 根据部门OID得到部门
  getDepartmentByOID(departmentOID) {
    return httpFetch.get(`${config.baseUrl}/api/departments/${departmentOID}`);
  },

  // 搜索人员
  searchUser(keyword, isCompany = true) {
    const params = { isCompany };
    return httpFetch.get(
      `${config.baseUrl}/api/search/users/by/${keyword}`,
      params
    );
  },

  // 打印单据
  printApplication(applicationOID) {
    return httpFetch.get(
      `${config.baseUrl}/api/loan/application/generate/pdf/${applicationOID}`
    );
  },

  // 打印单据
  printExpense(applicationOID) {
    return httpFetch.get(
      `${config.baseUrl}/api/expense/reports/generate/pdf/${applicationOID}`
    );
  },

  // 得到快速回复
  getQuickReply() {
    return httpFetch.get(`${config.baseUrl}/api/quick/reply`);
  },

  // 设置审批中标记
  /**
   *
   * @param entityOID 单据oid
   * @param userOID 当前操作人oid
   * @param approverOID 审批链上的approverOID
   * @returns {*|AxiosPromise}
   */
  setApproveTag(entityOID, userOID, approverOID) {
    return httpFetch.post(
      `${config.baseUrl}/api/approval/${entityOID}/flag?userOID=${userOID}&approverOID=${approverOID}`
    );
  },

  // 直接删除附件
  attachmentDelete(invoiceOid, attachmentId) {
    return httpFetch.delete(
      `${config.baseUrl}/api/finance/delete/attachment?invoiceOid=${invoiceOid}&attachmentId=${attachmentId}`
    );
  },

  // 获取账套下面的币种
  getAllCurrencyList(params) {
    return httpFetch.get(
      `${config.baseUrl}/api/currency/rate/list/all`,
      params
    );
  },

  // 获取推荐的费用
  /*
   * receipts: 发票信息 [{receiptTypeNo, taxCodes}]
   * applicationOID: 申请单oid
   * expenseReportOID: 报销单oid
   * customFormOID: 表单oid
   * */
  getRecommendExpenseTypeList(
    receipts,
    applicationOID,
    expenseReportOID,
    customFormOID,
    configResults,
    page = 0,
    size = 1
  ) {
    const params = {
      receipts,
      applicationOID,
      expenseReportOID,
      customFormOID,
      createManually: true,
      withReceipt: "Y",
      configResults,
      page,
      size,
    };
    return httpFetch.post(
      `${config.baseUrl}/api/invoice/history/record/v2`,
      params
    );
  },
  // 根据单号查询单据信息
  queryApplicationInfo(applicationNumber, tenantId) {
    const params = { applicationNumber, tenantId };
    return httpFetch.get(
      `${config.baseUrl}/api/invoice/applicationOID/by/applicationNumber`,
      params
    );
  },

  // 获取银行卡账户
  getUserBanks(param) {
    return httpFetch.get(
      `${config.baseUrl}/api/contact/bank/account/enable`,
      param
    );
  },

  // 查询信用事件
  getHonestEvent(params) {
    return httpFetch.get(
      `${config.baseUrl}/api/credit/reply/condition`,
      params
    );
  },

  // 得到用户信用信息
  getHonestInfo(userOID, jobId) {
    const params = { userOID };
    jobId && (params.jobId = jobId);
    return httpFetch.get(`${config.baseUrl}/api/credit/user/info`, params);
  },

  // 获取用户的信用时间记录
  getHonestHistory(params) {
    let res = "?";
    Object.keys(params).map((item) => {
      res += `${item}=${params[item]}&`;
    });
    res = res.substr(0, res.length - 1);
    return httpFetch.get(`${config.baseUrl}/api/credit/my/history${res}`);
  },

  // 获取公版access_token by ting.zhang
  getThirdPartyToken(param) {
    return httpFetch.get(`${config.baseUrl}/api/token/thirdParty`, param);
  },
  getFinanceConfig(params) {
    return httpFetch.get("/api/finance/config/companyConfig", params);
  },

  // 判断当前租户下存在成本中心项权限分配的数据(表单中成本中心控件是否需要清空)
  checkCostCenterNeedEmpty() {
    return httpFetch.get(`${config.baseUrl}/api/cost/center/by/tenant/visible`);
  },

  // 检查用户是否通过考核
  checkETraining() {
    return httpFetch.get(`${config.baseUrl}/api/exam`);
  },

  // 检查用户是否知晓通知
  checkNotice() {
    return httpFetch.get(`${config.baseUrl}/api/notice/state`);
  },

  // 检查用户是否通过考核
  confirmNotice() {
    return httpFetch.post(`${config.baseUrl}/api/notice/confirm`);
  },

  //获取DO默认值
  getDoPeople(params) {
    return httpFetch.get(`${config.baseUrl}/api/public/getDOPeople`, params);
  },

  // 获取一条成本中心详情
  getCostCenterItemDetailOne(costCenterItemOID) {
    return httpFetch.get(
      `${config.baseUrl}/api/my/cost/center/items/detail/${costCenterItemOID}`
    );
  },

  // 获取新关联的消费记录
  getNewAttExpense(invoiceOid) {
    // /api/bankbill/invoiceShow
    return httpFetch.get(
      `${config.baseUrl}/api/bankbill/invoiceShow?invoiceOid=${invoiceOid}`
    );
  },

  // 根据公司oid查公司的信息
  getQueryPrice(id) {
    return httpFetch.get(
      `${config.baseUrl}/api/expense/queryPrice?companyOID=${id}`
    );
  },

  // 批量新增分摊获取费用确认人列表
  getBatchAlloctionUser(params) {
    return httpFetch.post(
      `${config.baseUrl}/api/public/getBatchAlloctionUser`, params
    );
  },

  // 根据部门和当前人去查确认人
  getAlloctionUserByDepartment(params) {
    return httpFetch.get(
      `${config.baseUrl}/api/cost/center/check/cgm`, params[0]
    );
  },

  // 获取当前用户所在人员组是否是isGAndA
  getUserIsGAndA() {
    return httpFetch.get(
      `${config.baseUrl}/api/user/group/users/isConsumptions`).then((res) => {
        if(res.data) {
          sessionStorage.setItem(
            "isConsumptions",
            JSON.stringify(res.data)
          );
        }
        return res
      });
  },
};
